#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <mysql/mysql.h>
#include <ctype.h>

#include "../inc/tcp.h"
#include "../inc/register.h"
#include "../inc/cJSON.h"
#include "../inc/agreement.h"

// 好友申请列表项结构体（存储单条申请信息）
typedef struct
{
    int apply_id;         // 申请记录ID
    char from_userid[50]; // 申请人的userid
    char from_name[100];  // 申请人的昵称（假设user表有name字段）
    char apply_msg[101];  // 申请留言
    char create_time[20]; // 申请时间
} FriendApplyItem;

// 好友申请列表结构体
typedef struct
{
    int count;              // 申请总数
    FriendApplyItem *items; // 申请项数组
} FriendApplyList;

static void free_friend_apply_list(FriendApplyList *list);
static int get_user_id_by_userid(client_info_p client, const char *userid, int *out_id);
static int query_friend_apply_to_me(client_info_p client, int my_user_id, FriendApplyList *list);
static MYSQL_RES *mysql_query_with_result(MYSQL *db_conn, const char *sql);

// 处理获取好友申请列表的命令
void handle_get_friend_apply_list_cmd(client_info_p client, cJSON *root, cJSON *response)
{

    if (client == NULL || root == NULL || response == NULL)
    {
        cJSON_AddNumberToObject(response, "code", GET_FRIEND_APPLY_LIST_ERR_PARAM);
        cJSON_AddStringToObject(response, "message", "参数错误");
        return;
    }

    // 解析并校验 payload 和 userid
    cJSON *payload = cJSON_GetObjectItem(root, "payload");
    cJSON *userid_obj = (payload != NULL) ? cJSON_GetObjectItem(payload, "userid") : NULL;
    if (payload == NULL || userid_obj == NULL || !cJSON_IsString(userid_obj) || strlen(userid_obj->valuestring) == 0)
    {
        cJSON_AddNumberToObject(response, "code", GET_FRIEND_APPLY_LIST_ERR_PARAM);
        cJSON_AddStringToObject(response, "message", "参数错误");
        return;
    }
    const char *my_userid = userid_obj->valuestring;

    int my_user_id = 0;
    int ret = get_user_id_by_userid(client, my_userid, &my_user_id);
    if (ret != 0)
    {
        cJSON_AddNumberToObject(response, "code", GET_FRIEND_APPLY_LIST_ERR_USER_NOT_EXIST);
        cJSON_AddStringToObject(response, "message", "用户不存在");
        return;
    }

    FriendApplyList apply_list = {0};
    ret = query_friend_apply_to_me(client, my_user_id, &apply_list);
    if (ret != 0)
    {
        free_friend_apply_list(&apply_list); // 提前释放资源，避免内存泄漏
        cJSON_AddNumberToObject(response, "code", GET_FRIEND_APPLY_LIST_ERR_DB_QUERY);
        cJSON_AddStringToObject(response, "message", "数据库操作异常");
        return;
    }

    cJSON_AddNumberToObject(response, "code", GET_FRIEND_APPLY_LIST_SUCCESS);
    cJSON_AddStringToObject(response, "message", "success");

    cJSON *payload_res = cJSON_CreateObject();
    cJSON_AddItemToObject(response, "payload", payload_res);
    cJSON_AddNumberToObject(payload_res, "count", apply_list.count); // 申请总数

    // 构建申请列表数组
    cJSON *items_arr = cJSON_CreateArray();
    cJSON_AddItemToObject(payload_res, "items", items_arr);
    for (int i = 0; i < apply_list.count; i++)
    {
        cJSON *item = cJSON_CreateObject();
        cJSON_AddNumberToObject(item, "apply_id", apply_list.items[i].apply_id);
        cJSON_AddStringToObject(item, "from_userid", apply_list.items[i].from_userid);
        cJSON_AddStringToObject(item, "from_name", apply_list.items[i].from_name);
        cJSON_AddStringToObject(item, "apply_msg", apply_list.items[i].apply_msg);
        cJSON_AddStringToObject(item, "create_time", apply_list.items[i].create_time);
        cJSON_AddItemToArray(items_arr, item);
    }

    // 释放申请列表资源
    free_friend_apply_list(&apply_list);
}

// 释放好友申请列表内存
static void free_friend_apply_list(FriendApplyList *list)
{
    if (list == NULL)
        return;
    if (list->items != NULL)
    {
        free(list->items);
        list->items = NULL;
    }
    list->count = 0;
}

// 从user表通过userid查询id
static int get_user_id_by_userid(client_info_p client, const char *userid, int *out_id)
{
    if (client == NULL || userid == NULL || out_id == NULL)
        return -1;

    char sql[256];
    snprintf(sql, sizeof(sql),
             "SELECT id FROM `user` WHERE userid = '%s' LIMIT 1",
             userid);

    MYSQL_RES *res = mysql_query_with_result(client->db_conn, sql);
    if (res == NULL)
        return -2;

    MYSQL_ROW row = mysql_fetch_row(res);
    *out_id = (row && row[0]) ? atoi(row[0]) : 0;
    mysql_free_result(res);

    return (*out_id > 0) ? 0 : -3; // -3表示用户不存在
}

// 查询向我申请好友的列表
static int query_friend_apply_to_me(client_info_p client, int my_user_id, FriendApplyList *list)
{
    if (client == NULL || list == NULL || my_user_id <= 0)
        return -1;

    // 查询待处理的申请，关联user表获取申请人信息
    char sql[512];
    snprintf(sql, sizeof(sql),
             "SELECT fa.id, u.userid, u.name, fa.apply_msg, "
             "DATE_FORMAT(fa.create_time, '%%Y-%%m-%%d %%H:%%i') "
             "FROM friend_apply fa "
             "LEFT JOIN `user` u ON fa.apply_from = u.id "
             "WHERE fa.apply_to = %d AND fa.apply_status = %d "
             "ORDER BY fa.create_time DESC",
             my_user_id, APPLY_PENDING);

    MYSQL_RES *res = mysql_query_with_result(client->db_conn, sql);
    if (res == NULL)
        return -2;

    list->count = mysql_num_rows(res);
    if (list->count > 0)
    {
        list->items = (FriendApplyItem *)calloc(list->count, sizeof(FriendApplyItem));
        if (list->items == NULL)
        {
            mysql_free_result(res);
            return -3;
        }

        MYSQL_ROW row;
        int i = 0;
        while ((row = mysql_fetch_row(res)) != NULL)
        {
            // 填充申请项数据（注意字段顺序与SELECT一致）
            if (row[0])
                list->items[i].apply_id = atoi(row[0]);
            if (row[1])
                strncpy(list->items[i].from_userid, row[1], 49);
            if (row[2])
                strncpy(list->items[i].from_name, row[2], 99);
            if (row[3])
                strncpy(list->items[i].apply_msg, row[3], 100);
            if (row[4])
                strncpy(list->items[i].create_time, row[4], 19);
            i++;
        }
    }

    mysql_free_result(res);
    return 0;
}

// 辅助函数：执行查询并返回结果集（需自行释放）
static MYSQL_RES *mysql_query_with_result(MYSQL *db_conn, const char *sql)
{
    if (db_conn == NULL || sql == NULL)
        return NULL;
    if (mysql_query(db_conn, sql) != 0)
    {
        printf("SQL执行失败: %s (SQL: %s)\n", mysql_error(db_conn), sql);
        return NULL;
    }
    return mysql_store_result(db_conn);
}
